package com.hsy.swu.home

import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.core.content.ContextCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.google.android.material.internal.ViewUtils
import com.google.android.material.tabs.TabLayoutMediator
import com.hsy.swu.HomeActivity
import com.hsy.swu.MyConfig
import com.hsy.swu.R
import com.hsy.swu.clouddb.MyUser
import com.hsy.swu.databinding.DialogSchoolCalendarBinding
import com.hsy.swu.databinding.FragmentHomeBinding
import com.hsy.swu.databinding.OtherLeftDrawerRvItemBinding
import com.hsy.swu.home.course.CourseFragment
import com.hsy.swu.home.exam.ExamFragment
import com.hsy.swu.home.grade.GradeFragment
import com.hsy.swu.home.leftdrawer.AddCustomCourseActivity
import com.hsy.swu.home.leftdrawer.QQGroupActivity
import com.hsy.swu.home.leftdrawer.QuestionActivity
import com.hsy.swu.home.textbook.TextbookFragment
import com.hsy.swu.hsyutils.FragmentAdapter
import com.hsy.swu.hsyutils.HsyActivity
import com.hsy.swu.hsyutils.HsyFragment
import com.hsy.swu.hsyutils.MLog
import com.hsy.swu.hsyutils.addItem
import com.hsy.swu.hsyutils.saveImgToAlbum
import com.hsy.swu.hsyutils.setFont
import com.hsy.swu.spider.SwuSpiderHelper
import com.hsy.swu.spider.SwuSpiderService
import com.hsy.swu.utils.init
import com.hsy.swu.utils.setCustomView
import com.hsy.swu.version.VersionActivity
import com.hsy.swu.widget.goToSystemPermissionSetting
import com.hsy.swu.widget.pinCourseWidget
import com.hsy.swueasspider.utils.SwuEasSpiderUtils
import com.kongzue.dialogx.dialogs.CustomDialog
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.interfaces.OnBindView
import kotlinx.coroutines.launch

class HomeFragment : HsyFragment<FragmentHomeBinding, HomeFragmentViewModel>() {
    companion object {
        const val IS_CHECKED = "isChecked"
        var isChecked = "0" // 1 -> true, 0 -> false
    }

    private val tab1Name = "课表"
    private val tab2Name = "教材"
    private val tab3Name = "考试"
    private val tab4Name = "成绩"

    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            mViewModel.mBinder = service as SwuSpiderService.SwuSpiderBinder
            setViewPager2() // 获取 binder 之后再设置 viewPager2
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            MLog.attention("onServiceDisconnected >>> $name")
        }
    }

    override fun createViewModel(): HomeFragmentViewModel {
        return ViewModelProvider(requireActivity())[HomeFragmentViewModel::class.java]
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requireContext().bindService(
            Intent(requireContext(), SwuSpiderService::class.java),
            serviceConnection,
            Context.BIND_AUTO_CREATE
        )
        initLeftDrawerLinearLayout()

        setClick()
        setLeftDrawerListener()
        mBinding.btnRefresh.setOnClickListener {
            SwuSpiderHelper.startSwuSpiderService(requireContext())
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        requireContext().unbindService(serviceConnection)
    }

    private val courseFragment = CourseFragment()
    private val textbookFragment = TextbookFragment()
    private val examFragment = ExamFragment()
    private val gradeFragment = GradeFragment()
    private fun setViewPager2() {
        val otherPageAdapter = FragmentAdapter(childFragmentManager, lifecycle)
        otherPageAdapter.setPageList(
            if (MyConfig.currentWeek > 14) {
                listOf(
                    examFragment,
                    courseFragment,
                    textbookFragment,
                    gradeFragment
                )
            } else {
                listOf(
                    courseFragment,
                    textbookFragment,
                    examFragment,
                    gradeFragment
                )
            }
        )
        mBinding.viewPager2.adapter = otherPageAdapter
        mBinding.viewPager2.isSaveEnabled = false

        TabLayoutMediator(mBinding.tabLayout, mBinding.viewPager2) { tab, position ->
            when (position) {
                0 -> {
                    if (MyConfig.currentWeek > 11) {
                        tab.setCustomView(requireContext(), tab3Name, R.drawable.home_ic_exam)
                    } else {
                        tab.setCustomView(
                            requireContext(),
                            tab1Name,
                            R.drawable.home_ic_course_table
                        )

                    }
                    tab.customView?.findViewById<TextView>(R.id.title)?.visibility = View.VISIBLE
                }

                1 -> {
                    if (MyConfig.currentWeek > 11) {
                        tab.setCustomView(
                            requireContext(),
                            tab1Name,
                            R.drawable.home_ic_course_table
                        )
                    } else {
                        tab.setCustomView(requireContext(), tab2Name, R.drawable.home_ic_text_book)
                    }
                }

                2 -> {
                    if (MyConfig.currentWeek > 11) {
                        tab.setCustomView(requireContext(), tab2Name, R.drawable.home_ic_text_book)
                    } else {
                        tab.setCustomView(requireContext(), tab3Name, R.drawable.home_ic_exam)
                    }
                }

                3 -> {
                    tab.setCustomView(requireContext(), tab4Name, R.drawable.home_ic_grade)
                }
            }
        }.attach()

        mBinding.tabLayout.init()

        mBinding.viewPager2.registerOnPageChangeCallback(object : OnPageChangeCallback() {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)
                mBinding.tabLayout.setFont()
            }
        })
    }

    private fun initLeftDrawerLinearLayout() {
        if (mBinding.linearLayout.childCount != 0) return
        val allDrawerItem: List<Triple<Int, String, (OtherLeftDrawerRvItemBinding) -> Unit>> =
            listOf(
                /*Triple(R.drawable.left_drawer_ic_font, "切换字体") {
                    startActivity(Intent(requireActivity(), FontActivity::class.java))
                },*/
                Triple(R.drawable.left_drawer_ic_remind, "课程提醒 (beta)") {
                    MessageDialog.build()
                        .setTitle("启用课程提醒功能\n（请先打开通知权限）")
                        .setMessage("\t\t启用后会添加一个桌面小工具展示当日课程，并且上课前一段时间会有通知推送，因此，请先打开通知权限噢。\n\t\t建议打开锁屏通知与横幅通知（有些机型称为气泡通知）以获得及时的上课提醒。")
                        .setOkButton("跳转到设置通知管理") { _, _ ->
                            requireContext().goToSystemPermissionSetting()
                            return@setOkButton true
                        }
                        .setCancelButton("启用课程提醒") { _, _ ->
                            requireContext().pinCourseWidget()
                            return@setCancelButton false
                        }
                        .setButtonOrientation(LinearLayout.VERTICAL)
                        .show()
                },
                Triple(R.drawable.left_drawer_ic_renew, "检查更新") {
                    startActivity(Intent(requireActivity(), VersionActivity::class.java))
                },
                Triple(R.drawable.left_drawer_ic_qa, "常见问题 QA") {
                    startActivity(Intent(requireActivity(), QuestionActivity::class.java))
                },
                Triple(R.drawable.left_drawer_ic_calendar, "校历") {
                    val dialogBinding = DialogSchoolCalendarBinding.inflate(layoutInflater)
                    CustomDialog.build()
                        .setCustomView(object :
                            OnBindView<CustomDialog?>(dialogBinding.root) {
                            override fun onBind(p0: CustomDialog?, p1: View?) {
                                p0?.setMaskColor(
                                    ContextCompat.getColor(
                                        requireContext(),
                                        R.color.dialogMaskBlack
                                    )
                                )
                                dialogBinding.btnSave.setOnClickListener {
                                    dialogBinding.imageView.saveImgToAlbum("swu-${System.currentTimeMillis()}")
                                }
                            }
                        })
                        .show()
                },
                Triple(R.drawable.left_drawer_ic_add, "自定义增删课程") {
                    startActivity(Intent(requireContext(), AddCustomCourseActivity::class.java))
                },
                Triple(R.drawable.left_drawer_ic_share, "分享 APP") {
                    CustomDialog.build()
                        .setCustomView(object :
                            OnBindView<CustomDialog?>(R.layout.dialog_share) {
                            override fun onBind(p0: CustomDialog?, p1: View?) {
                                p0?.setMaskColor(
                                    ContextCompat.getColor(
                                        requireContext(),
                                        R.color.dialogMaskBlack
                                    )
                                )
                            }
                        })
                        .show()
                },
                Triple(R.drawable.left_drawer_ic_logout, "退出登录") {
                    MessageDialog.build()
                        .setTitle("退出登录确认")
                        .setCancelButton("点错了") { _, _ ->
                            return@setCancelButton false
                        }
                        .setOkButton("确认退出") { _, _ ->
                            lifecycleScope.launch {
                                SwuEasSpiderUtils.setCurrentCookie("")
                                MyUser.logOut(requireActivity() as HsyActivity<*, *>)
                            }
                            return@setOkButton false
                        }
                        .show()
                },
                Triple(R.drawable.left_drawer_ic_qq, "我有建议\n\t\t\t\tor\n我发现了 bug") {
                    startActivity(Intent(requireActivity(), QQGroupActivity::class.java))
                }
            )

        mBinding.linearLayout.addAllDrawerItem(allDrawerItem)

        /*val itemBinding =
            OtherLeftDrawerRvItemSwitchBinding.inflate(layoutInflater, mBinding.linearLayout, false)
        itemBinding.apply {
            icon.setImageResource(R.drawable.launcher)
            name.text = "数据自动更新"

            switchCompat.isChecked = isChecked == "1"
            switchCompat.setOnCheckedChangeListener { _, isChecked ->
                if (isChecked) {
                    requireContext().spWrite("1", IS_CHECKED)

                    MessageDialog.build()
                        .setTitle("注意❗❗❗")
                        .setMessage("开启数据自动更新后，在“选课期间”或者“你的账号正在其他设备登录了西南大学官网”时不要打开此App，否则其他设备上你正在使用的校园官网界面可能会由于账号多设备登录而被挤掉线噢！！！")
                        .setOkButton("知道了")
                        .show()
                } else {
                    requireContext().spWrite("0", IS_CHECKED)
                }
            }
        }
        mBinding.linearLayout.addItem(itemBinding)*/
    }

    private fun setClick() {
        /*val homeBottomDialog = CommentBottomDialog(requireContext())
        mBinding.btnComment.setOnClickListener {
            homeBottomDialog.show()
        }*/

        mBinding.btnMore.setOnClickListener {
            mBinding.drawerLayout.openDrawer(mBinding.leftDrawerScrollView)
        }
    }

    @SuppressLint("RestrictedApi")
    private fun LinearLayoutCompat.addAllDrawerItem(drawerItemList: List<Triple<Int, String, (OtherLeftDrawerRvItemBinding) -> Unit>>) {
        drawerItemList.forEachIndexed { index, triple ->
            val itemBinding = OtherLeftDrawerRvItemBinding.inflate(layoutInflater, this, false)
            itemBinding.apply {
                icon.setImageResource(triple.first)
                name.text = triple.second
                root.setOnClickListener { triple.third(this) }
            }
            if (index == 0) {
                // 最上面的 item要调整上边距
                val lp = itemBinding.root.layoutParams as ViewGroup.MarginLayoutParams
                lp.topMargin = ViewUtils.dpToPx(requireContext(), 15).toInt()
                itemBinding.root.layoutParams = lp
            }
            addItem(itemBinding)
        }
    }

    // 设置侧栏滑出事件监听
    private fun setLeftDrawerListener() {
        mBinding.drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
            override fun onDrawerStateChanged(newState: Int) {}
            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}

            override fun onDrawerOpened(drawerView: View) {
                (requireActivity() as HomeActivity).onBackPressedHomeFragmentListener = {
                    if (mBinding.drawerLayout.isOpen) {
                        mBinding.drawerLayout.close()
                    }
                }
            }

            override fun onDrawerClosed(drawerView: View) {
                (requireActivity() as HomeActivity).onBackPressedHomeFragmentListener = null
            }
        })
    }
}